package club.gggd.mimotion.util;

import club.gggd.mimotion.schedule.MiSchedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Description 项目启动成功后执行一次
 * @Author srx
 * @date 2022/4/7 15:33
 */
@Component
@Slf4j
public class FileCheck implements ApplicationRunner {

    @Value("${file.name}")
    public String name;

    @Value("${file.path}")
    public String path;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        File f = new File(path + name);
        if(!f.getParentFile().exists()){
            //不存在则创建父目录
            f.getParentFile().mkdirs();
        }
        if(!f.exists()){
            //不存在则创建文件
            log.info("创建存储文件：" + name);
            f.createNewFile();
        }else{
            log.info("读取存储文件：" + name);
            read();
        }
    }

    /**
     * 读取数据存入map
     * @throws IOException
     */
    public void read() throws IOException {
        FileInputStream in = null;
        try {
            Properties prop = new Properties();
            in = new FileInputStream(path + name);
            prop.load(in);
            //将数据放入map
            MiSchedule.info = new HashMap<String, String>((Map) prop);
        } finally {
            if(in != null){
                in.close();
            }
        }
    }
}
